package com.acme.mock;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class BankClient {
	static final String MES_UNKNOWN_HOST = "You are trying to connect to an unknown host!";
	static final String MES_INVALID_DATA = "Data received in unknown format";	
	static final String RESP_BYE = "bye";
	
	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;

	BankClient() {
	}

	void run() {
		try {
			// 1. creating a socket to connect to the server
			requestSocket = new Socket("localhost", 2004);
			System.out.println("Connected to localhost in port 2004");
			// 2. get Input and Output streams
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
			// 3: Communicating with the server
			do {
				message = receiveMessage();
				message = reader.readLine();
				sendMessage(message);
			} while (!message.equals(RESP_BYE));
		} catch (UnknownHostException e) {
			System.err.println(MES_UNKNOWN_HOST);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 4: Closing connection
			try {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("client>" + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	String receiveMessage() {
		String s = null;
		try {
			s = (String)in.readObject();
			System.out.println("server>" + s);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.err.println(MES_INVALID_DATA);
		}
		return s;
	}

	public static void startClient() {
		BankClient client = new BankClient();
		client.run();
	}

}
